class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        
        vector<vector<int>> vecRet;
        sort(intervals.begin(),intervals.end(),[](const vector<int>& p1,const vector<int>& p2){
            if(p1[0]==p2[0]){
                return p1[1]<p2[1];
            }
            return p1[0]<p2[0];
        });
        int left=-1,right=-1;
        for(int i=0;i<intervals.size();++i){
            if(-1==left){
                left=intervals[i][0],right=intervals[i][1];
            }
            else if(right<=intervals[i][1] && right>=intervals[i][0]){
                left=min(left,intervals[i][0]);
                right=max(right,intervals[i][1]);
            }
            else if(right<intervals[i][0]){
                vecRet.push_back({left,right});
                left=intervals[i][0],right=intervals[i][1];
            }
            else if(right>=intervals[i][1]){
                left=min(left,intervals[i][0]);
                right=max(right,intervals[i][1]);
            }
        }

        vecRet.push_back({left,right});

        return vecRet;
    }
};
